package com.agent.commons.config;

import com.agent.commons.other.ThreadLocal;
import com.agent.commons.utils.JWTUtil;
import com.agent.commons.utils.Sm4Util;
import feign.Client;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import feign.httpclient.ApacheHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * Feign相关配置类
 */
@Slf4j
@Configuration
public class FeignConfig implements RequestInterceptor {
    /**
     * 创建 Feign 客户端，并使用 Apache HttpClient 实现
     * @return
     */
    @Bean
    public Client feignClient() {
        log.info("创建 Feign连接池配置!");
        // 创建连接池管理器
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(200); // 总最大连接数
        connectionManager.setDefaultMaxPerRoute(50); // 每个路由的最大连接数

        // 创建 HttpClient 实例
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .build();
        return new ApacheHttpClient(httpClient);
    }

    /**
     * 在Feign调用前添加拦截参数
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //1.获取账号id
        String userId = ThreadLocal.getUserId();
        //2.获取账号名
        String userName = ThreadLocal.getUserName();
        //3.获取账号权限
        String userRole=ThreadLocal.getRole();
        log.error("权限:{}",userRole);
        log.info("用户ID:{},用户名:{}",userId,userName);
        //3.设置请求头，方便模块服务转发拦截
        //3.1 进行信息加密，后续拦截进行验证
        String key= Sm4Util.encrypt(userId+"-"+userName);
        requestTemplate.header("userId", userId);
        requestTemplate.header("userName", URLEncoder.encode(userName, StandardCharsets.UTF_8));
        requestTemplate.header("userRole", userRole);
        requestTemplate.header("key", key);
    }
}
